import {
	HTTP_REQUEST_URL
} from "../config";
let urlPrefix = HTTP_REQUEST_URL // HTTP_REQUEST_URL

function reDefault(val, def) {
	return (val || val === 0) ? val : def;
}

function valueByKeyString(data, key) {
	let leftIndex = key.indexOf("[");
	if (leftIndex < 0) {
		return reDefault(data[key], "");
	} else {
		let rightIndex = key.indexOf("]");
		if (rightIndex < 0) {
			return reDefault(data[key], "");
		} else {
			return reDefault(data[key.substring(0, leftIndex)][key.substring(leftIndex + 1, rightIndex)], "");
		}
	}
}

function getValue(data, keys) {
	try {
		let index = keys.indexOf(".");
		if (index < 0) {
			return valueByKeyString(data, keys);
		} else {
			let value = valueByKeyString(data, keys.substring(0, index));
			if (value) {
				return getValue(value, keys.substring(index + 1));
			} else {
				return "";
			}
		}
	} catch (e) {
		return "";
	}
}

function buildUrl(path) {
	if (path) return urlPrefix + 'api/' + path;
	return urlPrefix + 'api/'
}

function buildImgUrl(path) {
	if (path) {
		if (path.startsWith('http://') || path.startsWith('https://') || path.startsWith('@/') || path.startsWith(
				'blob:')) {
			return path;
		} else {
			return urlPrefix + path;
		}
	} else {
		return '';
	}
}

export {
	buildUrl,
	buildImgUrl,
	getValue
}